﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;

namespace Yoshizawa
{
    /// <summary>
    /// Form validation
    /// </summary>
    public class FormValidator
    {
        private readonly Form form;
        private readonly ErrorProvider errorProvider;
        private readonly object sync = new object();
        private readonly Dictionary<CancelEventHandler, Control> dic = new Dictionary<CancelEventHandler, Control>();

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="form">Form</param>
        public FormValidator(Form form)
        {
            if(null == form)
            {
                throw new ArgumentNullException("form");
            }

            this.form = form;
            this.form.AutoValidate = System.Windows.Forms.AutoValidate.Disable;
            this.errorProvider = new ErrorProvider(this.form)
            {
                BlinkStyle = ErrorBlinkStyle.NeverBlink,
            };

            this.IconAlignment = System.Windows.Forms.ErrorIconAlignment.MiddleLeft;
            this.IconPadding = 3;
        }

        /// <summary>
        /// Error Icon Alignment
        /// </summary>
        public ErrorIconAlignment IconAlignment
        {
            get;
            set;
        }

        /// <summary>
        /// Error Icon Padding
        /// </summary>
        public int IconPadding
        {
            get;
            set;
        }

        /// <summary>
        /// Validate
        /// </summary>
        /// <returns>true = Valid, false = InValid</returns>
        public bool Validate()
        {
            try
            {
                this.errorProvider.Clear();
                this.form.AutoValidate = System.Windows.Forms.AutoValidate.EnablePreventFocusChange;

                return this.form.ValidateChildren(ValidationConstraints.Enabled);
            }
            finally
            {
                this.form.AutoValidate = System.Windows.Forms.AutoValidate.Disable;
            }
        }

        /// <summary>
        /// Add validation to control
        /// </summary>
        /// <typeparam name="TControl">Control Type</typeparam>
        /// <typeparam name="TValue">Value Type</typeparam>
        /// <param name="control">Control</param>
        /// <param name="getter">Value Getter</param>
        /// <param name="validations">validations</param>
        public void Add<TControl, TValue>(
            TControl control,
            Func<TControl, TValue> getter,
            params Func<TValue, string>[] validations) where TControl : Control
        {
            if(null == control)
            {
                throw new ArgumentNullException("control");
            }

            if (null == getter)
            {
                throw new ArgumentNullException("getter");
            }

            lock (this.sync)
            {
                CancelEventHandler handler = (object sender, CancelEventArgs e) =>
                {
                    TValue value = getter(control);

                    foreach (var validation in validations)
                    {
                        var errorMessgae = validation(value);

                        if (!string.IsNullOrWhiteSpace(errorMessgae))
                        {
                            this.errorProvider.SetIconAlignment(control, this.IconAlignment);
                            this.errorProvider.SetIconPadding(control, this.IconPadding);
                            this.errorProvider.SetError(control, errorMessgae);
                            e.Cancel = true;
                            control.Focus();
                            return;
                        }
                    }
                };

                this.dic.Add(handler, control);
                control.Validating += handler;
            }
        }

        /// <summary>
        /// Clear validation of control
        /// </summary>
        /// <param name="control">Control</param>
        public void Clear(Control control)
        {
            if (null == control)
            {
                throw new ArgumentNullException("control");
            }

            lock(this.sync)
            {
                this.dic.Where(s => s.Value == control)
                    .ToList()
                    .ForEach(pair =>
                    {
                        CancelEventHandler handler = pair.Key;
                        control.Validating -= handler;
                        this.dic.Remove(handler);
                    });
            }
        }

        /// <summary>
        /// Get validation error of control
        /// </summary>
        /// <param name="control">Control</param>
        /// <returns>Error Message</returns>
        public string GetError(Control control)
        {
            if(null == control)
            {
                throw new ArgumentNullException("control");
            }

            return this.errorProvider.GetError(control);
        }
    }
}
